<template>
  <div class="dialog-for-column">
    <fks-dialog
      v-if="Visible"
      :visible.sync="Visible"
      :append-to-body="true"
      :title="LANG.TOP_MANAGE"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
    >
      <template slot="title">
        <i class="fks-icon-edit" />
        <span>{{ LANG.TOP_MANAGE }}</span>
      </template>

      <div
        v-loading="loading"
        class="column-edit"
      >
        <!-- 标题 -->
        <p class="label">
          {{ LANG.CONTENT_MSG }}
        </p>
        <fks-form
          :model="titleForm"
          labfks-position="left"
          labfks-width="84px"
        >
          <fks-form-item
            :span="24"
            :label="LANG.CONTENT_TITLE"
          >
            <fks-button
              type="text"
              @click="rowClick"
            >
              {{
                contentTitle
              }}
            </fks-button>
          </fks-form-item>
        </fks-form>

        <!-- 旧的状态显示 -->
        <p
          class="label"
          style="margin-top: 16px;"
        >
          {{ LANG.CURRENT_STATUS }}
        </p>
        <fks-form
          ref="Form"
          :model="Form"
          labfks-position="left"
          labfks-width="84px"
        >
          <fks-form-item
            :span="12"
            :label="LANG.CURRENT_STATUS"
          >
            <span>
              <fks-tag :type="getTagTypeByStatus(statusCode)">{{
                getStatusDescription(statusCode)
              }}</fks-tag>
            </span>
          </fks-form-item>

          <fks-form-item
            :span="12"
            :label="LANG.TOP"
          >
            <fks-switch
              v-model="Form.isTop"
              disabled
              active-value="1"
              inactive-value="0"
            />
          </fks-form-item>

          <!-- 这边可以再处理下，显示用户设置的发布时间 -->
          <fks-form-item
            :span="24"
            :label="
              userSetDate
                ? LANG.CURRENT_USER_SET_TIME
                : LANG.CURRENT_PUBLISH_TIME
            "
          >
            <fks-date-picker
              v-if="oldPublishTime.id || userSetDate"
              v-model="Form.publishDate"
              disabled
              type="datetimerange"
              style="width: 100%;"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              :start-placeholder="LANG.BEGIN_TIME"
              :end-placeholder="LANG.END_TIME"
              align="right"
            />
            <span v-else>{{ LANG.UNSET }}</span>
          </fks-form-item>

          <div v-if="Form.isTop == '1'">
            <fks-form-item
              :span="24"
              :label="LANG.CURRENT_TOP_TIME"
            >
              <fks-date-picker
                v-if="oldTopTime.id"
                v-model="Form.topDate"
                disabled
                type="datetimerange"
                style="width: 100%;"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                :start-placeholder="LANG.BEGIN_TIME"
                :end-placeholder="LANG.END_TIME"
                align="right"
              />
            </fks-form-item>
          </div>
        </fks-form>

        <!-- 新的状态设置 -->
        <p
          class="label"
          style="margin-top: 16px;"
        >
          {{ LANG.NEW_STATUS }}
        </p>
        <fks-form
          ref="newForm"
          :model="newForm"
          labfks-position="left"
          labfks-width="84px"
        >
          <fks-form-item
            :span="12"
            :label="LANG.NEW_STATUS"
          >
            <span>
              <fks-tag :type="getTagTypeByStatus(newStatusCode)">{{
                getStatusDescription(newStatusCode)
              }}</fks-tag>
            </span>
          </fks-form-item>

          <fks-form-item
            :span="12"
            :label="LANG.TOP"
          >
            <fks-switch
              v-model="newForm.isTop"
              active-value="1"
              inactive-value="0"
              @change="topChange(newForm.isTop)"
            />
          </fks-form-item>

          <fks-form-item
            :span="24"
            :label="LANG.NEW_PUBLISH_TIME"
            prop="publishDate"
            required
          >
            <span slot="label">
              <span class="span-box">
                <span>{{ LANG.NEW_PUBLISH_TIME }}</span>
                <fks-tooltip placement="top-start">
                  <div
                    slot="content"
                    style=" font-size: 14px;line-height: 20px;"
                    class="tips-container"
                  >
                    {{ LANG.TIME_SET_TIP }}
                  </div>
                  <i class="fks-icon-question" />
                </fks-tooltip>
              </span>
            </span>
            <fks-date-picker
              v-model="newForm.publishDate"
              :disabled="operateType != 'publish'"
              type="datetimerange"
              style="width: 100%;"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss"
              :start-placeholder="LANG.BEGIN_TIME"
              :end-placeholder="LANG.END_TIME"
              align="right"
              @change="checkPublish"
            />
          </fks-form-item>

          <div v-if="newForm.isTop == '1'">
            <fks-form-item
              :span="24"
              :label="LANG.NEW_TOP_TIME"
              prop="topDate"
              required
            >
              <fks-date-picker
                v-model="newForm.topDate"
                type="datetimerange"
                style="width: 100%;"
                value-format="yyyy-MM-dd HH:mm:ss"
                :picker-options="pickerOptions"
                :start-placeholder="LANG.BEGIN_TIME"
                :end-placeholder="LANG.END_TIME"
                align="right"
                @change="checkTop"
              />
            </fks-form-item>
          </div>
        </fks-form>
      </div>

      <template slot="footer">
        <section>
          <fks-button
            type="primary"
            icon="fks-icon-check"
            :loading="submitLoading"
            @click="clickHandle"
          >
            {{ LANG.SUBMIT }}
          </fks-button>
        </section>
      </template>
    </fks-dialog>
    <dialog-read
      :id="contentId"
      :title="contentTitle"
      :visible="read_dialog_visible"
      @close="closeReadDialog"
    />
  </div>
</template>

<script>
import {
  addContentStatus,
  getLastPublish,
  updateContentStatus,
  getStatusDescription,
  getTagTypeByStatus
} from '@/modules/Content/api'
import { saveRevision } from '../../../api/index'
import { ENUM } from '@/store/State/stateTypes'
import DialogRead from '@/modules/Content/components/DialogRead/index'
export default {
  name: 'TopManage',
  components: {
    DialogRead
  },
  props: {
    visible: {
      type: Boolean
    },
    contentTitle: {
      type: String
    },
    contentId: {
      type: String
    },
    userSetDate: {
      type: String
    },
    statusCode: {
      type: String,
      default: ''
    },
    operateType: {
      type: String,
      default: 'publish'
    }
  },
  data() {
    return {
      loading: true,
      read_dialog_visible: false,
      submitLoading: false,
      Visible: false,
      Form: {},
      newForm: {},
      titleForm: {},
      publishDate: [],
      topDate: [],
      now: '',
      oldPublishTime: {},
      oldTopTime: {},
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              end.setTime(end.getTime() + 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
        // disabledDate(time) {
        //   return time.getTime() <= Date.now() - 3600 * 1000 * 24
        // }
      }
    }
  },
  computed: {
    newStatusCode() {
      if (
        this.newForm.isTop === '1' &&
        this.newForm.topDate &&
        this.newForm.topDate[0] <= this.now &&
        this.newForm.topDate[1] >= this.now
      ) {
        return 'TOP'
      }
      if (
        this.newForm.publishDate &&
        this.newForm.publishDate[0] <= this.now &&
        this.newForm.publishDate[1] >= this.now
      ) {
        return 'PUBLISH'
      }
      return 'REVOKE'
    },
    contentStatus() {
      return this.$store.state[ENUM].contentStatus || []
    },
    forever() {
      return '2099-12-31 23:59:59'
    },
  },
  watch: {
    visible(val) {
      this.Visible = val
      if (val) {
        this.resetData()
        this.initData()
      }
    }
  },
  mounted() {
    this.resetData()
  },
  methods: {
    updateNow() {
      this.now = this.$dayjs().locale('zh-cn').format('YYYY-MM-DD HH:mm:ss')
    },
    checkPublish() {
      this.updateNow()
      if (this.newForm.publishDate) {
        if (this.newForm.publishDate[0] < this.now)
          this.newForm.publishDate[0] = this.now
        if (this.newForm.publishDate[1] < this.newForm.publishDate[0])
          this.newForm.publishDate[1] = this.forever
        this.checkTop()
      } else {
        this.$set(this.newForm, 'topDate', null)
      }
    },
    checkTop() {
      this.updateNow()
      if (this.newForm.topDate) {
        if (
          this.newForm.topDate[0] < this.newForm.publishDate[0] ||
          this.newForm.topDate[0] > this.newForm.publishDate[1]
        )
          this.$set(this.newForm.topDate, '0', this.newForm.publishDate[0])
        if (this.newForm.topDate[0] < this.now)
          this.$set(this.newForm.topDate, '0', this.now)
        if (
          this.newForm.topDate[1] > this.newForm.publishDate[1] ||
          this.newForm.topDate[1] < this.newForm.topDate[0] ||
          this.newForm.topDate[1] < this.newForm.topDate[0]
        )
          this.$set(this.newForm.topDate, '1', this.newForm.publishDate[1])
      }
    },
    closeReadDialog() {
      this.read_dialog_visible = false
    },
    /**
     * @description: 跳转详情页
     * @param {Object}  row
     *                  row.id为内容id
     */
    rowClick() {
      this.read_dialog_visible = true
    },

    /**
     * @description: 打开置顶开关后初始化时间
     */
    topChange(type) {
      if (type == '1' && this.newForm.publishDate != null) {
        this.$set(
          this.newForm,
          'topDate',
          JSON.parse(JSON.stringify(this.newForm.publishDate))
        )
      }
    },

    /**
     * @description: 当前·内容状态
     */
    getCurrentStatus() {
      /**
       * @description: 获得未来最接近的发布和置顶状态
       *               该方法用于展示将要到来的发布和置顶
       */
      this.oldPublishTime = {}
      this.oldTopTime = {}
      getLastPublish(this.contentId)
        .then((res) => {
          if (res.status) {
            this.Form.isTop = '0'
            if (res.data.length > 0) {
              for (let i = 0; i < res.data.length; i++) {
                let item = res.data[i]
                if (item.status == 'PUBLISH') {
                  this.$set(this.Form, 'publishDate', [
                    item.startTime,
                    item.endTime
                  ])
                  this.$set(this.newForm, 'publishDate', [
                    item.startTime,
                    item.endTime
                  ])
                  this.oldPublishTime = item
                }
                if (item.status == 'TOP') {
                  this.Form.isTop = '1'
                  this.newForm.isTop = '1'
                  this.$set(this.Form, 'topDate', [
                    item.startTime,
                    item.endTime
                  ])
                  this.$set(this.newForm, 'topDate', [
                    item.startTime,
                    item.endTime
                  ])
                  this.oldTopTime = item
                }
              }
            } else {
              if (this.userSetDate) {
                this.$set(this.Form, 'publishDate', [
                  this.userSetDate,
                  this.forever
                ])
                this.$set(this.newForm, 'publishDate', [
                  this.userSetDate,
                  this.forever
                ])
              } else {
                this.$set(this.newForm, 'publishDate', [this.now, this.forever])
              }
            }
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * @description: 根据当前语言，获取status.code对应的status.name
     * @param {String}  status.code
     * @return {String} status.name
     */
    getStatusDescription(statusCode) {
      return getStatusDescription(statusCode, this.contentStatus, this.$lang)
    },

    /**
     * @description: 获得状态status.code对应的表演颜色
     */
    getTagTypeByStatus(statusCode) {
      return getTagTypeByStatus(statusCode)
    },

    clickHandle() {
      let that = this
      this.$refs['newForm'].validate((valid) => {
        if (valid) {
          this.submitLoading = true
          that.onSubmit()
        } else {
          that.$message.error(this.LANG.ERROR_UNDO_WRITE)
          return
        }
      })
    },
    /**
     * @description: 保存处理
     */
    onSubmit() {
      this.updateNow()
      this.publishDate = JSON.parse(JSON.stringify(this.newForm.publishDate))
      let publishStartDate
      let publishEndDate

      // publish时间判断
      if (this.publishDate == null || this.publishDate.length < 1) {
        publishStartDate = this.now
        publishEndDate = this.forever
      } else {
        publishStartDate = this.publishDate[0]
        publishEndDate = this.publishDate[1]
      }

      //时间校验
      if (
        publishEndDate == null ||
        publishEndDate == '' ||
        publishEndDate < this.now
      ) {
        publishEndDate = this.forever
      }

      if (
        publishStartDate == null ||
        publishStartDate == '' ||
        publishStartDate < this.now
      ) {
        publishStartDate = this.now
      }

      if (publishEndDate < publishStartDate) {
        this.$message({
          type: 'error',
          message: '发布结束时间不能前于开始时间'
        })
        this.submitLoading = false
        return
      }
      this.publishDate = [publishStartDate, publishEndDate]

      //top时间判断
      if (this.newForm.isTop == '1') {
        this.topDate = JSON.parse(JSON.stringify(this.newForm.topDate))
        let topStartDate
        let topEndDate

        if (this.topDate == null || this.topDate.length < 1) {
          topStartDate = publishStartDate
          topEndDate = publishEndDate
        } else {
          topStartDate = this.topDate[0]
          topEndDate = this.topDate[1]
        }

        //时间校验
        if (
          topStartDate == null ||
          topStartDate == '' ||
          topStartDate < publishStartDate ||
          topStartDate > publishEndDate
        ) {
          topStartDate = publishStartDate
        }
        if (
          topEndDate == null ||
          topEndDate == '' ||
          topEndDate < publishStartDate ||
          topEndDate > publishEndDate
        ) {
          topEndDate = publishEndDate
        }

        if (topEndDate < topStartDate) {
          this.$message({
            type: 'error',
            message: '置顶结束时间不能前于开始时间'
          })
          this.submitLoading = false
          return
        }

        this.topDate = [topStartDate, topEndDate]
      }

      this.publish()
    },

    /**
     * @description: 发布处理
     */
    publish() {
      //入口为置顶
      if (this.operateType == 'top') {
        this.updateTop()
        return
      }

      //入口为发布
      //添加一个内容的历史版本
      if (this.statusCode == 'AUDIT') {
        saveRevision(this.contentId)
      }

      //存在将要到来的发布状态时，修改它
      //不存在时添加
      if (this.oldPublishTime.id) {
        this.updateStatus()
      } else {
        this.addStatus()
      }
    },

    /**
     * @description: 有已经设定的publish和top时候，更新状态信息
     */
    updateStatus() {
      let publish = JSON.parse(JSON.stringify(this.oldPublishTime))

      publish.startTime = this.Form.publishStartDate
      publish.endTime = this.Form.publishEndDate

      this.updateContentStatus(publish)
    },

    /**
     * @description: 有已经设定的publish和top时，更新top信息
     */
    updateTop() {
      //存在将要到来的置顶
      if (this.oldTopTime.id) {
        let top = JSON.parse(JSON.stringify(this.oldTopTime))

        //新的设定有置顶
        if (this.newForm.isTop == '1') {
          top.startTime = this.topDate[0]
          top.endTime = this.topDate[1]
        } else {
          top.deleteFlag = -1
        }

        this.updateContentStatus(top)
      }
      //不存在将要到来的置顶
      else {
        //新的设定有置顶
        if (this.newForm.isTop == '1') {
          let top = [
            {
              status: 'TOP',
              startTime: this.topDate[0],
              endTime: this.topDate[1],
              contentId: this.contentId
            }
          ]

          this.addContentStatus(top)
        } else {
          this.submit()
        }
      }
    },

    /**
     * @description: 不存在publish和top，新增将要到来的发布状态
     */
    addStatus() {
      let statusList = []

      let publish = {
        status: 'PUBLISH',
        startTime: this.publishDate[0],
        endTime: this.publishDate[1],
        contentId: this.contentId
      }
      statusList.push(publish)

      if (this.newForm.isTop == '1') {
        let top = {
          status: 'TOP',
          startTime: this.topDate[0],
          endTime: this.topDate[1],
          contentId: this.contentId
        }
        statusList.push(top)
      }

      this.addContentStatus(statusList)
    },

    /**
     * @description: 内容新增状态
     */
    addContentStatus(temp) {
      addContentStatus(temp).then((res) => {
        if (res.status) {
          this.missionComplete()
        } else {
          this.submitLoading = false
        }
      })
    },

    /**
     * @description: 内容更新状态
     */
    updateContentStatus(temp) {
      updateContentStatus(temp)
        .then((res) => {
          if (res.status) {
            this.missionComplete()
          } else {
            this.submitLoading = false
          }
        })
        .catch(() => {
          this.submitLoading = false
        })
    },

    /**
     * @description: 更新状态完成后，弹出提示并隐藏弹框
     */
    missionComplete() {
      setTimeout(() => {
        this.$message({
          type: 'success',
          message: this.LANG.UPDATE_SUCCESS
        })
        this.submit()
      }, 1000)
    },

    close() {
      this.$emit('close')
      this.resetData()
    },
    submit() {
      this.submitLoading = false
      this.$emit('submit')
    },
    cancel() {
      this.close()
    },
    resetData() {
      this.updateNow()
      this.Form = {
        isTop: 0,
        publishDate: [],
        topDate: []
      }
      this.newForm = JSON.parse(JSON.stringify(this.Form))
      this.oldTopTime = {}
      this.oldPublishTime = {}
      this.loading = true
    },
    initData() {
      this.resetData()
      this.getCurrentStatus()
    }
  }
}
</script>

<style scoped lang="scss">
::v-deep .fks-dialog__body {
  padding-bottom: 0;
}

.label {
  margin-top: 0;
  margin-bottom: 16px;
  font-weight: 600 !important;
  font-size: 16px !important;
  color: #191919;
}
</style>
